package com.wowoai.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.StreamProgress;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.util.UUID;


/**
 * @className: FileDownloadUtils
 * @author: wdg
 */
@Slf4j
public class FileDownloadUtils {

    /**
     *  下载文件
     * @param fileUrl 文件的URL
     * @param diskPath 保存到磁盘的地址
     * @return 文件路径
     */
    public static String downLoadFromUrl(String fileUrl, String diskPath) {
        String path = null;
        if (fileUrl != null) {
            //文件后缀
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("."));
            try {
                String uuidName = UUID.randomUUID().toString();
                File file = new File(diskPath);
                if (!file.exists()) {
                    //创建文件夹
                    boolean mkdir = file.mkdirs();
                    if (!mkdir) {
                        throw new RuntimeException("创建文件夹失败，路径为：" + diskPath);
                    }
                }
                path = diskPath + File.separator + uuidName + fileName;
                long beginTime = System.currentTimeMillis();
                //带进度显示的文件下载
                HttpUtil.downloadFile(fileUrl, FileUtil.file(path), new StreamProgress() {
                    @Override
                    public void start() {
                        log.info("开始下载，时间为：{}", beginTime);
                    }

                    @Override
                    public void progress(long l) {

                    }

                    @Override
                    public void finish() {
                        log.info("下载完成 : {}", System.currentTimeMillis() - beginTime);
                    }
                });
            } catch (Exception e) {
                log.info("下载异常，异常信息为：" + e.getMessage());
            }
        }
        return path;
    }

    /**
     * 下载文件
     * @param fileUrl 文件url
     * @param type 文件type .jpg .png ...
     * @return 返回文件
     */
    public static File downloadFile(String fileUrl, String type) {
        if (fileUrl != null) {
            try {
                //建立连接
                URL url = new URL(fileUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //设置请求方式
                connection.setRequestMethod("GET");
                //设置超时时间
                connection.setConnectTimeout(10 * 1000);
                //输入流
                InputStream inputStream = connection.getInputStream();
                int len = 0;
                byte[] test = new byte[1024];
                //设置文件名称
                String fileName = UUID.randomUUID() + "." + type;
                //目标文件
                File outFile = new File("/tmp/" + fileName);
                //输出流，输出的目标文件
                BufferedOutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(outFile.toPath()));
                //以流的方式上传
                while ((len = inputStream.read(test)) != -1) {
                    outputStream.write(test, 0, len);
                }
                //关闭流，不然消耗资源
                inputStream.close();
                outputStream.close();
                return outFile;
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
}
